import { createI18n } from 'vue-i18n'
import zhCN from './locales/zh-CN.json'
import zhTW from './locales/zh-TW.json'
import enUS from './locales/en-US.json'
import jaJP from './locales/ja-JP.json'

// 支持的语言类型
export type SupportedLocale = 'zh-CN' | 'zh-TW' | 'en-US' | 'ja-JP'

const getStoredLocale = (): SupportedLocale => {
  const stored = localStorage.getItem('echo_role_language') as SupportedLocale
  const validLocales: SupportedLocale[] = ['zh-CN', 'zh-TW', 'en-US', 'ja-JP']
  
  // 验证存储的语言是否有效
  if (stored && validLocales.includes(stored)) {
    console.log('[i18n] Loading stored locale:', stored)
    return stored
  }
  
  console.log('[i18n] No valid stored locale found, using default: zh-CN')
  return 'zh-CN'
}

const i18n = createI18n({
  legacy: false, // 使用 Composition API 模式
  locale: getStoredLocale(), // 默认语言
  fallbackLocale: 'zh-CN', // 回退语言
  messages: {
    'zh-CN': zhCN,
    'zh': zhCN, 
    'zh-TW': zhTW,
    'en-US': enUS,
    'en': enUS, 
    'ja-JP': jaJP,
    'ja': jaJP 
  }
})

export default i18n

export const setLocale = (locale: SupportedLocale) => {
  console.log('[i18n] Setting locale to:', locale)
  
  i18n.global.locale.value = locale as any
  
  localStorage.setItem('echo_role_language', locale)
  
  document.documentElement.setAttribute('lang', locale)
  
  console.log('[i18n] Current locale after setting:', i18n.global.locale.value)
  console.log('[i18n] Available locales:', Object.keys(i18n.global.messages.value))
  
  const event = new CustomEvent('language-changed', { detail: { locale } })
  window.dispatchEvent(event)
  
  i18n.global.locale.value = locale as any
}

export const getCurrentLocale = (): SupportedLocale => {
  return i18n.global.locale.value as SupportedLocale
}

export const supportedLocales = [
  { value: 'zh-CN', label: '简体中文', flag: '🇨🇳' },
  { value: 'zh-TW', label: '繁体中文', flag: '🇹🇼' },
  { value: 'en-US', label: 'English', flag: '🇺🇸' },
  { value: 'ja-JP', label: '日本語', flag: '🇯🇵' }
] 